package network;

import com.jme3.app.SimpleApplication;
import com.jme3.network.HostedConnection;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.system.JmeContext;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MainServer extends SimpleApplication {
    protected Server server;

    public static void main(String[] args) {
        MainServer app = new MainServer();
	app.start(JmeContext.Type.Headless);
    }

    @Override
    public void simpleInitApp() {
	try {
	    server = Network.createServer(NetworkUtil.PORT);
	    server.start();
	    ServerListener serverListener = new ServerListener();
	    server.addConnectionListener(serverListener);
	    server.addMessageListener(serverListener);
	    NetworkUtil.registerMessages();
	} catch (IOException ex) {
	    Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, "Unable to initialize server on port: "+NetworkUtil.PORT, ex);
	}
    }

    @Override
    public void destroy() {
	if(server.hasConnections()) {
	    for(HostedConnection connection : server.getConnections())
		connection.close("Server shutting down...");
	}
	server.close();
	super.destroy();
    }
}
